package com.tron.dobest.commonsio;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.RegexFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.List;

/**
 * @description commonsIo
 * @auther TRON
 * @create 2020-02-17
 */
public class Start {
    public static void main(String[] args) throws IOException {

        //获取打包目录中的文件，resource目录的文件会被打包到target/classes目录下
        URL url = ClassLoader.getSystemResource("test.txt");
        System.out.println("ClassLoader.getSystemResource <------> "+url.getPath());

        //到项目的根目录获取文件，如果写相对路径，从项目基础包目录下找。路径可以拆开写
        File file = FileUtils.getFile("src/main/resources/","test.txt");
        System.out.println(file.getAbsolutePath());
        System.out.println(file.exists());

        //从指定目录中获取指定文件
        File file1 = FileUtils.getFile(new File("src/main/resources"), "test.txt");
        System.out.println(file1.exists());

        //复制文件到指定目录
        try {
            FileUtils.copyFile(file1,new File("test1.txt"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //向文件追加内容
        try {
            FileUtils.write(new File("test1.txt"),"\nefg","utf-8",true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取文件列表，第三个值为是否递归
        System.out.println("-------------FileUtils.listFiles(new File(\"src/main/resources\"), null, true);-------------");
        Collection<File> files = FileUtils.listFiles(new File("src/main/resources"), null, true);
        files.forEach(System.out::println);
        System.out.println("------------end--------------");

        //根据后缀过滤器获取文件
        System.out.println("--------------FileUtils.listFiles(new File(\"src/main/resources\"), new SuffixFileFilter(\".txt\"), null)-----------------");
        Collection<File> files1 = FileUtils.listFiles(new File("src/main/resources"), new SuffixFileFilter(".txt"), null);
        files1.forEach(System.out::println);
        System.out.println("----------------end---------------");

        //根据正则过滤器获取文件
        System.out.println("--------------FileUtils.listFiles(new File(\"src/main/resources\"), new RegexFileFilter(\".*test.*\"), null);---------------");
        Collection<File> files2 = FileUtils.listFiles(new File("src/main/resources"), new RegexFileFilter(".*test.*"), null);
        files2.forEach(System.out::println);
        System.out.println("----------------end---------------");

        //按行读取文件
        final List<String> strings = FileUtils.readLines(new File("src\\main\\resources\\test.txt"), "utf-8");
        System.out.println("FileUtils.readLines <------> "+strings);

        //获取文件大小
        final long l = FileUtils.sizeOf(new File("src\\main\\resources\\test.txt"));
        System.out.println("FileUtils.sizeOf <------> "+l);
    }
}
